package x.ovo.wechat.bot.plugin;

import picocli.CommandLine;
import x.ovo.wechat.bot.core.Constant;
import x.ovo.wechat.bot.core.command.CommandExcutor;
import x.ovo.wechat.bot.core.plugin.Plugin;

import java.util.Arrays;
import java.util.Objects;

/**
 * 命令管理的命令执行器
 *
 * @author ovo on 2024/07/24.
 */
@CommandLine.Command(name = "command-manager", aliases = {"cm"}, description = "命令管理")
public class CmExecutor extends CommandExcutor {

    @CommandLine.Parameters(paramLabel = "command", defaultValue = "", index = "0", description = "需要操作的命令(仅支持主命令，不支持别名)", arity = "0..1")
    private String command;

    public CmExecutor(Plugin plugin) {
        super(plugin);
    }

    @CommandLine.Command(name = "-a", aliases = {"--add"}, description = "添加可执行的用户")
    public String add(@CommandLine.Parameters(paramLabel = "users", description = "用户") String[] users) {
        try {
            Arrays.stream(users).forEach(user -> this.ctx.getCommandManager().addPermission(this.command, user));
            this.ctx.getCommandManager().savePermissions();
            return "成功添加 [" + this.command + "] 的可执行人 " + users.length + " 位";
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    @CommandLine.Command(name = "-r", aliases = {"--remove"}, description = "移除可执行的用户")
    public String remove(@CommandLine.Parameters(paramLabel = "users", description = "用户") String[] users) {
        try {
            Arrays.stream(users).forEach(user -> this.ctx.getCommandManager().addPermission(this.command, user));
            this.ctx.getCommandManager().savePermissions();
            return "成功移除 [" + this.command + "] 的可执行人 " + users.length + " 位";
        } catch (Exception e) {
            return e.getMessage();
        }
    }

    @CommandLine.Command(name = "-l", aliases = {"--list"}, description = "显示可执行的用户")
    public String list() {
        try {
            StringBuilder sb = new StringBuilder();
            if (Objects.isNull(this.command) || this.command.isBlank()) {
                this.ctx.getCommandManager().getPermissions().forEach((key, value) -> sb.append(key).append(": ").append(value).append("\n"));
            } else {
                sb.append("可执行命令 [").append(this.command).append("] 的用户：").append(Constant.delimiter)
                        .append(this.ctx.getCommandManager().getPermission(this.command));
            }
            return sb.toString();
        } catch (Exception e) {
            return e.getMessage();
        }
    }
}
